import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Item from '../Item'
import './index.css'

export default class List extends Component {
  state = {
    list: [],
    isFirst: true, // 是否第一次进入
    isLoading: false,
    errInfo: '' // 存储返回的错误信息
  }

  // 一进入页面就订阅消息
  componentDidMount() {
    this.token = PubSub.subscribe('updateListSomeStatus', (_, stateObj) => {
      this.setState({ ...stateObj })
    })
  }

  // 卸载组件就取消订阅
  componentWillUnmount() {
    PubSub.unsubscribe(this.token)
  }

  render() {
    const { list, isLoading, isFirst, errInfo } = this.state
    return (
      <div>
        {isFirst ? (
          <div>欢迎来到当前组件</div>
        ) : isLoading ? (
          <div>Loading...</div>
        ) : errInfo ? (
          <div>网络错误，小主稍后再试吧</div>
        ) : !list.length ? (
          <div>数据为空，换个搜索词试试吧</div>
        ) : (
          <div className="list-box">
            {list.map((item) => (
              <Item key={item.id} {...item} />
            ))}
          </div>
        )}
      </div>
    )
  }
}
